<template>
<div class="semAdoptCouponSelect">
  <div class="tags-outer-block">
    <div class="tags-block" :class="{'is-full-screen': isFullScreen}">
      <el-tag
        v-for="(item, index) in selected"
        :key="index"
        :closable="!disabled"
        @close="$emit('remove', {value: item})">{{ generateSelectName(item) }}</el-tag>
    </div>
    <el-link class="full-screen-btn" :underline="false" @click="isFullScreen = !isFullScreen">
      <i v-if="isFullScreen" class="el-icon-bottom-left"></i>
      <i v-else class="el-icon-top-right"></i>
    </el-link>
  </div>
  <div class="table-block" v-if="!disabled">
    <search-block type="flex">
      <el-form inline :model="model">
        <el-form-item label="名称:">
          <el-input v-model="model.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="品种:">
          <el-cascader
            v-model="varietyVal"
            clearable
            :options="adoptCate"
            :props="{
              label: 'cateName',
              value: 'cateCode'
            }"></el-cascader>
        </el-form-item>
      </el-form>
      <div class="adopt-buttons">
        <el-button type="primary" @click="search">查询</el-button>
      </div>
    </search-block>
    <y-table
        ref="table"
        border
        pagination
        :getDataWay="getDataWay"
        :columns="columns">
      <el-table-column slot="SKU" label="选择SKU" align="center" header-align="center" width="80">
        <template v-slot="{row}">
          <el-popover
            :value="row.showPopover">
            <div class="row-checkbox">
              <el-checkbox
                v-for="item in row.skuData"
                :key="item.value"
                style="display: block"
                @change="val => changeSelect(row, item, val)"
                v-model="item.checked">{{item.label}}</el-checkbox>
            </div>
            <div slot="reference" class="el-button el-button--primary el-button--mini" @click="initSelect(row)">sku</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column slot="imgUrl" label="图标" align="center" header-align="center" width="80">
        <template v-slot="{row}">
          <img v-if="row.imgUrl" style="height: 40px" :src="generateMediaUrl({fileOpenUrl: row.imgUrl})"/>
        </template>
      </el-table-column>
      <el-table-column slot="name" label="名称" align="center" header-align="center" min-width="300">
        <template v-slot="{row}">
          {{row.name + (row.memo ? '(' + row.memo + ')' : '')}}
        </template>
      </el-table-column>
      <el-table-column slot="variety" label="品种" align="center" header-align="center" min-width="100">
        <template v-slot="{row}">
          {{getVarietyName(row.kind, row.variety)}}
        </template>
      </el-table-column>
    </y-table>
  </div>
</div>
</template>

<script>
export default {
  name: "semAdoptCouponSelect",
  inject: ['generateMediaUrl'],
  props:{
    selected: {
      type: Array,
      default: () => []
    },
    adoptCate: Array,
    adoptMap: {
      type: Object,
      default: () => ({})
    },
    adoptSkuMap: {
      type: Object,
      default: () => ({})
    },
    disabled:{
      type: Boolean,
      default: false
    }
  },
  computed:{
    getDataWay(){
      return {
        dataType: 'url',
        data: this.$api.adopt.queryAdoptInfoList,
        param: this.model
      }
    },
    varietyVal:{
      get(){
        let ary = [];
        if(this.model.kind){
          ary.push(this.model.kind);
          if(this.model.variety){
            ary.push(this.model.variety);
          }
        }
        return ary;
      },
      set(val = []){
        val = val || [];
        [this.model.kind = '', this.model.variety = ''] = val;
      }
    }
  },
  data(){
    return{
      model:{
        name: '',
        kind: '',
        variety: '',
        //enableFlag: '1'
      },
      columns: [{
        label: "选择sku",
        prop: "SKU",
        template: true
      },{
        label: "商品图标",
        prop: "imgUrl",
        template: true,
      },{
        label: "名称",
        prop: "name",
        template: true
      },{
        label: "价格",
        prop: "price",
        template: true
      },{
        label: "品种",
        prop: "variety",
        template: true
      }],
      isFullScreen: false,//最大化
    }
  },
  methods:{
    search(){
      this.$refs['table'].loadData(this.model);
    },
    generateSelectName(str){
      let [adoptId, skuId] = str.split('/');
      return this.adoptMap[adoptId] ? this.adoptMap[adoptId] + '/' + (this.adoptSkuMap[skuId] || '') : '';
    },
    getVarietyName(kind, variety){
      if(!kind || !this.adoptCate.length) return '';
      let str = ''
      let kindObj = this.adoptCate.find(cd => cd.cateCode === kind);
      if(!kindObj) return '';
      str += kindObj.cateName;
      if(variety && kindObj.children && kindObj.children.length){
        let varietyObj = kindObj.children.find(vd => vd.cateCode === variety);
        if(varietyObj){
          str += '/' + varietyObj.cateName;
        }
      }
      return str;
    },
    async initSelect(row){
      //如果没加载sku列表，先加载列表
      if(!row.skuData || !row.skuData.length){
        let info = await this.initSku(row);
        this.$set(row, 'skuData', info.map(item => ({
          value: item.id,
          label: Object.values(JSON.parse(item.specJson)).join(';'),
          checked: false
        })));
      }else{
        row.skuData.map(item => {
          this.$set(item, 'checked', false);
        })
      }
      let mySelect = this.selected.filter(str => str.startsWith(row.id + '/'));
      mySelect.map(str => {
        let sku = str.split('/').pop();
        let obj = row.skuData.find(item => item.value === sku);
        if(obj){
          this.$set(obj, 'checked', true);
        }
      })
    },
    initSku(row){
      return new Promise(resolve => {
        this.$yAxios({
          url: this.$api.adopt.queryAdoptSkuList,
          data:{
            adoptId: row.id,
            specCodes: []
          },
          loading: true
        }, info => {
          resolve(info || []);
        }, e => {
          resolve([]);
        });
      })
    },
    changeSelect(adoptObj, skuObj, val){
      this.adoptMap[adoptObj.id] = adoptObj.name;
      this.adoptSkuMap[skuObj.value] = skuObj.label;
      let event = val ? 'add' : 'remove';
      let emitObj = {
        value: adoptObj.id + '/' + skuObj.value,
        rootName: adoptObj.name,
        skuName: skuObj.label
      };
      this.$emit(event, emitObj);
    }
  }
}
</script>

<style scoped lang="less">
.semAdoptCouponSelect{
  .tags-outer-block{
    width: 100%;
    border: @common-border;
    display: flex;
    .tags-block{
      width: calc(100% - 20px);
      border-right: @common-border;
      display: flex;
      align-items: center;
      height: 50px;
      overflow-x: auto;
      overflow-y: hidden;
      white-space: nowrap;
      padding: 2.5px 20px;
      position: relative;
      &.is-full-screen{
        //display: block;
        height: auto;
        min-height: 50px;
        overflow: visible;
        white-space: unset;
        flex-wrap: wrap;
      }
      >.el-tag{
        margin: 2.5px 5px;
      }
      >.full-screen-btn{
        align-self: flex-start;
      }
    }
  }
  .table-block{
    padding: 20px;
    border: @common-border;
    border-top: none;
  }
}
</style>